// pages/exam/index.js
const app = getApp()
const api = require('../../utils/api')
const Promise = require('../../utils/es6-promise.min.js')
Page({

    /**
   * 页面的初始数据
   */
    data: {
        questionList: [], //
        currentIndex: 0, //当前题目
        count: -1, //题目总数
        page: 1, //分页页码
        pageSize: 2, //
        userRank: null, //
        nodata: false, //没有更多
        singleOptionIndex: -1, //当前选项（单选）
        userArray: [], //用户选择答案的数组
    },

    /**
   * 上一题
   */
    prev: function () {

    },

    /**
   * 下一题
   */
    next: function () {
        let currentQuestion = this.data.questionList[this.data.currentIndex]
        switch(currentQuestion.type){
            case 0:
                let answerArray = []
                answerArray.push(currentQuestion.answer)
                this.checkAnswer(answerArray, this.data.userArray)
                break;
            case 1:
                let answerArray2 = currentQuestion.answer.split(',')
                this.checkAnswer(answerArray2, this.data.userArray)
                break;
        }
    },

    /**
   * 比较数组是否相同
   */
    equalArray: function (arr1, arr2) {
        for (let i = 0; i < arr2.length; i++) {
            if (arr1.indexOf(arr2[i]) === -1) {
                return false
            }
        }
        return true
    },
    /**
   * 答题完毕提示
   */
    endTip:function (){
        api.showModalPromisified({
            title: '鼎玉理财提示您',
            content: `练习已完毕，是否重来一次`,
            confirmColor: '#333',
            cancelColor: '#333',
            cancelText: '退出',
            confirmText: '重来一次'
        }).then(res => {
            if (res.confirm) {
                wx.redirectTo({
                    url:'/pages/exam/index'
                })
            } else if (res.cancel) {
                wx.navigateBack({
                    delta: 1
                })
            }
        })
    },
    /**
   * 正误验证
   */
    checkAnswer: function (answerArr, userArr) {
        let bol = this.equalArray(answerArr, userArr)
        bol ? this.correctHandle() : this.errorHandle()
    },
    /**
   * 正确处理
   */
    correctHandle: function () {
        //下一题是最后一道时，提前预加载下页题库
        if((this.data.currentIndex+1) === (this.data.questionList.length-1)){
            this.requstExercise().then(res=>{
                console.log(res)
                this.data.currentIndex++
                this.setData({
                    currentIndex: this.data.currentIndex,
                    singleOptionIndex: -1,
                })    
            })
            return
        }
        if(this.data.nodata){
            this.endTip()
            return
        }
        this.data.currentIndex++
        this.setData({
            currentIndex: this.data.currentIndex,
            singleOptionIndex: -1,
        }) 
    },
    /**
   * 错误处理
   */
    errorHandle: function () {
        let currentQuestion = this.data.questionList[this.data.currentIndex]

        api.showModalPromisified({
            title: '很遗憾，答错了',
            content: `我要再试试`,
            confirmColor: '#d56f47',
            cancelColor: '#999',
            cancelText: '退出',
            confirmText: '继续'
        }).then(res => {
            //请求错题接口
            if (res.confirm) {
                //重置选项未选中
                currentQuestion.selection.map(value => {
                    value.isSelect = false
                })
                this.setData({
                    singleOptionIndex: -1,
                    questionList: this.data.questionList,
                    userArray: []
                })
            } else if (res.cancel) {
                wx.navigateBack({
                    delta: 1
                })
            }
        })

    },
    /**
   * 单选
   */
    singleSelect: function (e) {
        let index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item,
            userArray = []
        userArray.push(item.option)
        this.setData({
            singleOptionIndex: index,
            userArray
        })

    },
    /**
   * 多选
   */
    multipleSelect: function (e) {
        let index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item,
            currentQuestion = this.data.questionList[this.data.currentIndex]

        currentQuestion.selection[index].isSelect = currentQuestion.selection[index].isSelect ? false : true //选中和取消
        currentQuestion.selection[index].isSelect ? this.data.userArray.push(item.option) : this.data.userArray.splice(this.data.userArray.indexOf(item.option), 1) //用户选择或者取消答案

        this.setData({
            questionList: this.data.questionList,
            userArray: this.data.userArray
        })



    },
    /**
   * 题库空提示
   */
    countZeroTip:function(res){
        if (res.data.count < 1) {
            api.showModalPromisified({
                title: '鼎玉理财提示您',
                content: `暂无练习题库，请等待更新`,
                confirmColor: '#d56f47',
                showCancel: false,
                confirmText: '确定'
            }).then(() => {
                wx.navigateBack({
                    delta: 1
                })
            })
        }
    },
    /**
   * 请求练习题目
   */
    requstExercise: function () {

        return new Promise((resolve, reject) => {

            //没有用户段位信息时返回
            if (!this.data.userRank) return;
            api.post('/QBank/QBankList', {
                Lv: this.data.userRank.rankKnowledge.rankLv,
                page: this.data.page,
                pageSize: this.data.pageSize
            }).then(res => {

                //题库无数据时返回上一页
                this.countZeroTip(res)

                //组装选项数据
                res.data.data.map((value, index) => {
                    value.selection = []
                    for (let p in value) {
                        if (/(opt)/.test(p) && value[p]) {
                            value.selection.push({
                                option: p,
                                answer: value[p],
                                isSelect: false
                            })
                        }
                    }
                })

                let questionList = this.data.questionList.concat(res.data.data),
                    count = res.data.count,
                    page = ++this.data.page
                this.setData({
                    questionList,
                    count,
                    page,
                })

                //题库取完时
                if (res.data.count === this.data.questionList.length) {
                    this.setData({
                        nodata: true
                    })
                }
                resolve()
            })

        })
    },

    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function (options) {

        //请求用户段位数据
        api.post('/init/userRank')
            .then(res => {
            this.setData({
                userRank: res.data
            })
            this.requstExercise()//请求练习题目
        })

    },

    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function () {

    },

    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function () {

    },

    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function () {

    },

    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function () {

    },

    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function () {

    },

    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function () {

    },

    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function () {

    }
})